<?php
/**
 * @brief 商家模块
 * @class Seller
 * @author chendeshan
 * @datetime 2014/7/19 15:18:56
 */
class Seller extends IController implements sellerAuthorization
{
	public $layout = 'seller';

	/**
	 * @brief 初始化检查
	 */
	public function init()
	{

	}
	/**
	 * @brief 商品添加中图片上传的方法
	 */
	public function goods_img_upload()
	{
	 	//调用文件上传类
		$photoObj = new PhotoUpload();
		$photo    = current($photoObj->run());

		//判断上传是否成功，如果float=1则成功
		if($photo['flag'] == 1)
		{
			$result = array(
				'flag'=> 1,
				'img' => $photo['img']
			);
		}
		else
		{
			$result = array('flag'=> $photo['flag']);
		}
		echo JSON::encode($result);
	}
	/**
	 * @brief 商品添加和修改视图
	 */
	public function goods_edit()
	{
		$goods_id = IFilter::act(IReq::get('id'),'int');

		//初始化数据
		$goods_class = new goods_class($this->seller['seller_id']);

		//获取所有商品扩展相关数据
		$data = $goods_class->edit($goods_id);

		if($goods_id && !$data)
		{
			die("没有找到相关商品！");
		}

		$this->setRenderData($data);
		$this->redirect('goods_edit');
	}
	//商品更新动作
	public function goods_update()
	{
		$id       = IFilter::act(IReq::get('id'),'int');
		$callback = IReq::get('callback');
		$callback = strpos($callback,'seller/goods_list') === false ? '' : $callback;

		//检查表单提交状态
		if(!$_POST)
		{
			die('请确认表单提交正确');
		}

		//初始化商品数据
		unset($_POST['id']);
		unset($_POST['callback']);
		$goodsObject = new goods_class($this->seller['seller_id']);
		$goodsObject->update($id,$_POST);

		$callback ? $this->redirect($callback) : $this->redirect("goods_list");
	}
	/**
	 * @brief 商品添加中图片上传的方法
	 */
	public function seller_img_upload()
	{
	    //调用文件上传类
	    $photoObj = new PhotoUpload();
	    $photo    = current($photoObj->run());
	     // echo "aaa";
	     // die;
	    //判断上传是否成功，如果float=1则成功
	    if($photo['flag'] == 1)
	    {
	        $result = array(
	            'flag'=> 1,
	            'img' => $photo['img']
	        );
	    }
	    else
	    {
	        $result = array('flag'=> $photo['flag']);
	    }
	    echo JSON::encode($result);
	}
	//商品列表
	public function goods_list()
	{
		$seller_id = $this->seller['seller_id'];
		$searchArray = Util::getUrlParam('search');
		$searchParam = http_build_query($searchArray);
		$condition = Util::goodsSearch(IReq::get('search'));
		$where = "go.seller_id='$seller_id' ";
		$where .= $condition ? " and ".$condition : "";
		$join = isset($searchArray['search']['category_id']) ? " left join category_extend as ce on ce.goods_id = go.id " : "";
		$page   = IReq::get('page') ? IFilter::act(IReq::get('page'),'int') : 1;

		$goodHandle = new IQuery('goods as go');
		$goodHandle->order  = "go.id desc";
		$goodHandle->fields = "distinct go.id,go.name,go.sell_price,go.market_price,go.store_nums,go.img,go.is_del,go.seller_id,go.is_share,go.sort";
		$goodHandle->where  = $where;
		$goodHandle->page	= $page;
		$goodHandle->join	= $join;

		$this->goodHandle = $goodHandle;

		$goods_info = array();
		$goods_info['seller_id'] = $seller_id;
		$goods_info['searchParam'] = $searchParam;
		$this->setRenderData($goods_info);
		$this->redirect('goods_list');
	}

	//商品列表
	public function wholesale_goods()
	{
	    $seller_id = $this->seller['seller_id'];
	    $sellerDB = new IModel('seller');
	    $sellerArray = $sellerDB->getObj('id ='.$seller_id);
	    //$searchArray = Util::getUrlParam('search');
	    //$searchParam = http_build_query($searchArray);
	    //$condition = Util::goodsSearch(IReq::get('search'));
	    //$where = "go.seller_id='$seller_id' ";
	    //$where .= $condition ? " and ".$condition : "";
	    $where = "go.plate = '".$sellerArray['plate_id']."' and go.xiaoshou_type = 1 and go.is_del = 0";
	    $join = isset($searchArray['search']['category_id']) ? " left join category_extend as ce on ce.goods_id = go.id " : "";
	    $page   = IReq::get('page') ? IFilter::act(IReq::get('page'),'int') : 1;
	
	    $goodHandle = new IQuery('goods as go');
	    $goodHandle->order  = "go.id desc";
	    $goodHandle->fields = "distinct go.id,go.name,go.sell_price,go.market_price,go.store_nums,go.img,go.is_del,go.seller_id,go.is_share,go.sort";
	    $goodHandle->where  = $where;
	    $goodHandle->page	= $page;
	    $goodHandle->join	= $join;
	
	    $this->goodHandle = $goodHandle;
	
	    $goods_info = array();
	    $goods_info['seller_id'] = $seller_id;
	    //$goods_info['searchParam'] = $searchParam;
	    $this->seller_id = $seller_id;
	    $this->seller_name = $sellerArray['seller_name'];
	    $this->setRenderData($goods_info);
	    $this->redirect('wholesale_goods');
	}
	
	//商品列表
	public function goods_report()
	{
		$seller_id = $this->seller['seller_id'];
		$condition = Util::goodsSearch(IReq::get('search'));

		$where  = 'go.seller_id='.$seller_id;
		$where .= $condition ? " and ".$condition : "";
		$join = isset($_GET['search']['category_id']) ? " left join category_extend as ce on ce.goods_id = go.id " : "";

		$goodHandle = new IQuery('goods as go');
		$goodHandle->order  = "go.id desc";
		$goodHandle->fields = "go.*";
		$goodHandle->where  = $where;
		$goodHandle->join	= $join;
		$goodList = $goodHandle->find();

		$reportObj = new report('goods');
		$reportObj->setTitle(array("商品名称","分类","售价","库存"));
		foreach($goodList as $k => $val)
		{
			$insertData = array(
				$val['name'],
				goods_class::getGoodsCategory($val['id']),
				$val['sell_price'],
				$val['store_nums'],
			);
			$reportObj->setData($insertData);
		}
		$reportObj->toDownload();
	}

	//商品删除
	public function goods_del()
	{
		//post数据
	    $id = IFilter::act(IReq::get('id'),'int');

	    //生成goods对象
	    $goods = new goods_class();
	    $goods->seller_id = $this->seller['seller_id'];

	    if($id)
		{
			if(is_array($id))
			{
				foreach($id as $key => $val)
				{
					$goods->del($val);
				}
			}
			else
			{
				$goods->del($id);
			}
		}
		$this->redirect("goods_list");
	}


	//商品状态修改
	public function goods_status()
	{
	    $id        = IFilter::act(IReq::get('id'),'int');
		$is_del    = IFilter::act(IReq::get('is_del'),'int');
		$is_del    = $is_del === 0 ? 3 : $is_del; //不能等于0直接上架
		$seller_id = $this->seller['seller_id'];

		$goodsDB = new IModel('goods');
		$goodsDB->setData(array('is_del' => $is_del));

	    if($id)
		{
			$id = is_array($id) ? join(",",$id) : $id;
			$goodsDB->update("id in (".$id.") and seller_id = ".$seller_id);
		}
		$this->redirect("goods_list");
	}

	//规格删除
	public function spec_del()
	{
		$id = IFilter::act(IReq::get('id'),'int');

		if($id)
		{
			$idString = is_array($id) ? join(',',$id) : $id;
			$specObj  = new IModel('spec');
			$specObj->del("id in ( {$idString} ) and seller_id = ".$this->seller['seller_id']);
			$this->redirect('spec_list');
		}
		else
		{
			$this->redirect('spec_list',false);
			Util::showMessage('请选择要删除的规格');
		}
	}
	//修改排序
	public function ajax_sort()
	{
		$id   = IFilter::act(IReq::get('id'),'int');
		$sort = IFilter::act(IReq::get('sort'),'int');

		$goodsDB = new IModel('goods');
		$goodsDB->setData(array('sort' => $sort));
		$goodsDB->update("id = {$id} and seller_id = ".$this->seller['seller_id']);
	}

	//咨询回复
	public function refer_reply()
	{
		$rid     = IFilter::act(IReq::get('refer_id'),'int');
		$content = IFilter::act(IReq::get('content'),'text');

		if($rid && $content)
		{
			$tb_refer = new IModel('refer');
			$seller_id = $this->seller['seller_id'];//商户id
			$data = array(
				'answer' => $content,
				'reply_time' => ITime::getDateTime(),
				'seller_id' => $seller_id,
				'status' => 1
			);
			$tb_refer->setData($data);
			$tb_refer->update("id=".$rid);
		}
		$this->redirect('refer_list');
	}
	
	/**
	 * @brief我的供应商商品订单
	 */
	public function supplier_order(){
	    $payment = new IQuery('payment');
	    $payment->fields = 'id,name,type';
	    $payments = $payment->find();
	    $items = array();
	    foreach($payments as $pay)
	    {
	        $items[$pay['id']]['name'] = $pay['name'];
	        $items[$pay['id']]['type'] = $pay['type'];
	    }
	    $this->payments = $items;
	    
	    $seller_id = $this->seller['seller_id'];
	    $sellerDB        = new IModel('seller');
		$sellerRow = $sellerDB->getObj('id = '.$seller_id);
		$userDB        = new IModel('user');
		$userRow = $userDB->getObj('username = "'.$sellerRow['seller_name'].'"');
	    $where  = "o.user_id=".$userRow['id']." and o.if_del=0";
	    $page   = IReq::get('page') ? IFilter::act(IReq::get('page'),'int') : 1;
	    $orderHandle = new IQuery('supplier as o');
	    $orderHandle->order  = "o.id desc";
	    $orderHandle->where  = $where;
	    $orderHandle->page  = $page;
	    $this->orderHandle   = $orderHandle;
	    $this->redirect('supplier_order');
	}
	
	/**
	 * @brief查看订单
	 */
	public function order_show()
	{
		//获得post传来的值
		$order_id = IFilter::act(IReq::get('id'),'int');
		$data = array();
		if($order_id)
		{
			$order_show = new Order_Class();
			$data = $order_show->getOrderShow($order_id,0,$this->seller['seller_id']);
			if($data)
			{
		 		//获取地区
		 		$data['area_addr'] = join('&nbsp;',area::name($data['province'],$data['city'],$data['area']));

			 	$this->setRenderData($data);
				$this->redirect('order_show',false);
			}
		}
		if(!$data)
		{
		    //供应商
		    $order_show = new Order_Class();
		    $supplierData = $order_show->getSupplierOrderShow($order_id,0,$this->seller['seller_id']);
		    if ($supplierData){
		        //获取地区
		        $supplierData['area_addr'] = join('&nbsp;',area::name($supplierData['province'],$supplierData['city'],$supplierData['area']));
		        
		        $this->setRenderData($supplierData);
		        $this->redirect('supplier_order_show',false);
		    }
		    if (!$supplierData){
		        $this->redirect('order_list');
		    }
		}
	}
	
	/**
	 * @brief查看虚拟订单
	 */
	public function vr_order_show()
	{
	    //获得post传来的值
	    $order_no = IFilter::act(IReq::get('order_no'));
	    $data = array();
	    if($order_no)
	    {
	        $order_show = new Order_Class();
	        $data = $order_show->getVrOrderShow($order_no,0,$this->seller['seller_id']);
	        if($data)
	        {
	            //获取地区
	            //$data['area_addr'] = join('&nbsp;',area::name($data['province'],$data['city'],$data['area']));
	           
	            $this->setRenderData($data);
	            $this->redirect('vr_order_show',false);
	        }
	    }
	    if(!$data)
	    {
	        $this->redirect('vr_order_list');
	    }
	}
	/**
	 * @brief 发货订单页面
	 */
	public function order_deliver()
	{
		$order_id = IFilter::act(IReq::get('id'),'int');
		$data     = array();

		if($order_id)
		{
			$order_show = new Order_Class();
			$data = $order_show->getOrderShow($order_id);
			if($data)
			{
				$this->setRenderData($data);
				$this->redirect('order_deliver');
			}
		}
		if(!$data)
		{
			IError::show("订单信息不存在",403);
		}
	}
	
	/**
	 * @brief 发货订单页面
	 */
	public function supplier_order_deliver()
	{
	    $order_id = IFilter::act(IReq::get('id'),'int');
	    $data     = array();
	  
	    if($order_id)
	    {
	        $order_show = new Order_Class();
	        $data = $order_show->getSupplierOrderShow($order_id);
	        if($data)
	        {
	            $this->setRenderData($data);
	            $this->redirect('supplier_order_deliver');
	        }
	    }
	    if(!$data)
	    {
	        IError::show("订单信息不存在",403);
	    }
	}
	
	/**
	 * @brief 发货操作
	 */
	public function order_delivery_doc()
	{
	 	//获得post变量参数
	 	$order_id = IFilter::act(IReq::get('id'),'int');

	 	//发送的商品关联
	 	$sendgoods = IFilter::act(IReq::get('sendgoods'),'int');

	 	if(!$sendgoods)
	 	{
	 		die('请选择要发货的商品');
	 	}

	 	$result = Order_Class::sendDeliveryGoods($order_id,$sendgoods,$this->seller['seller_id'],'seller');
	 	if($result === true)
	 	{
	 		$this->redirect('order_list');
	 	}
	 	else
	 	{
	 		IError::show($result);
	 	}
	}
	
	/**
	 * @brief 发货操作
	 */
	public function supplier_order_delivery_doc()
	{
	    //获得post变量参数
	    $order_id = IFilter::act(IReq::get('id'),'int');
	
	    //发送的商品关联
	    $sendgoods = IFilter::act(IReq::get('sendgoods'),'int');
	
	    if(!$sendgoods)
	    {
	        die('请选择要发货的商品');
	    }
	
	    $result = Order_Class::sendSupplierGoods($order_id,$sendgoods,$this->seller['seller_id'],'seller');
	    if($result === true)
	    {
	        $this->redirect('supplier_order_list');
	    }
	    else
	    {
	        IError::show($result);
	    }
	}
	
	/**
	 * @brief 实物订单列表
	 */
	public function order_list()
	{
		$seller_id = $this->seller['seller_id'];
		$searchArray = Util::getUrlParam('search');
		$searchParam = http_build_query($searchArray);
		$condition = Util::orderSearch(IReq::get('search'));
		$where  = "o.seller_id='$seller_id' and o.if_del=0 and o.status not in(3,4)";
		$where .= $condition ? " and ".$condition : "";
		$page   = IReq::get('page') ? IFilter::act(IReq::get('page'),'int') : 1;

		$orderHandle = new IQuery('order as o');
		$orderHandle->order  = "o.id desc";
		$orderHandle->where  = $where;
		$orderHandle->page	 = $page;
		$this->orderHandle   = $orderHandle;
		$order_info = array();
		$order_info['seller_id'] = $seller_id;
		$order_info['searchParam'] = $searchParam;
		$this->setRenderData($order_info);
		$this->redirect('order_list');
	}
	/**
	 * @brief 虚拟订单列表
	 */
	public function vr_order_list()
	{
	    $seller_id = $this->seller['seller_id'];
	    $searchArray = Util::getUrlParam('search');
	    $searchParam = http_build_query($searchArray);
	    $condition = Util::orderSearch(IReq::get('search'));
	    $where  = "o.seller_id='$seller_id' and o.if_del=0 and o.status not in(3,4)";
	    $where .= $condition ? " and ".$condition : "";
	    $page   = IReq::get('page') ? IFilter::act(IReq::get('page'),'int') : 1;
	
	    $orderHandle = new IQuery('vr_order as o');
	    $orderHandle->order  = "o.id desc";
	    $orderHandle->where  = $where;
	    $orderHandle->page	 = $page;
	    $this->orderHandle   = $orderHandle;
	    $order_info = array();
	    $order_info['seller_id'] = $seller_id;
	    $order_info['searchParam'] = $searchParam;
	    $this->setRenderData($order_info);
	    $this->redirect('vr_order_list');
	}
	
	/**
	 * @brief 供应商订单列表
	 */
	public function supplier_order_list()
	{
	    $seller_id = $this->seller['seller_id'];
	    $searchArray = Util::getUrlParam('search');
	    $searchParam = http_build_query($searchArray);
	    $condition = Util::orderSearch(IReq::get('search'));
	    $where  = "o.seller_id='$seller_id' and o.if_del=0 and o.status not in(3,4)";
	    $where .= $condition ? " and ".$condition : "";
	    $page   = IReq::get('page') ? IFilter::act(IReq::get('page'),'int') : 1;
	
	    $orderHandle = new IQuery('supplier as o');
	    $orderHandle->order  = "o.id desc";
	    $orderHandle->where  = $where;
	    $orderHandle->page	 = $page;
	    $this->orderHandle   = $orderHandle;
	    $order_info = array();
	    $order_info['seller_id'] = $seller_id;
	    $order_info['searchParam'] = $searchParam;
	    $this->setRenderData($order_info);
	    $this->redirect('supplier_order_list');
	}
	
	//订单导出 Excel
	public function order_report()
	{
		$seller_id = $this->seller['seller_id'];
		$condition = Util::orderSearch(IReq::get('search'));

		$where  = "o.seller_id = ".$seller_id." and o.if_del=0 and o.status not in(3,4)";
		$where .= $condition ? " and ".$condition : "";

		//拼接sql
		$orderHandle = new IQuery('order as o');
		$orderHandle->order  = "o.id desc";
		$orderHandle->fields = "o.*,p.name as payment_name";
		$orderHandle->join   = "left join payment as p on p.id = o.pay_type";
		$orderHandle->where  = $where;
		$orderList = $orderHandle->find();

		$reportObj = new report('order');
		$reportObj->setTitle(array("订单编号","日期","收货人","电话","订单金额","实际支付","支付方式","支付状态","发货状态","商品信息"));

		foreach($orderList as $k => $val)
		{
			$orderGoods = Order_class::getOrderGoods($val['id']);
			$strGoods   = "";
			foreach($orderGoods as $good)
			{
				$strGoods .= "商品编号：".$good['goodsno']." 商品名称：".$good['name'];
				if ($good['value']!='') $strGoods .= " 规格：".$good['value'];
				$strGoods .= "<br />";
			}

			$insertData = array(
				$val['order_no'],
				$val['create_time'],
				$val['accept_name'],
				$val['telphone'].'&nbsp;'.$val['mobile'],
				$val['payable_amount'],
				$val['real_amount'],
				$val['payment_name'],
				Order_Class::getOrderPayStatusText($val),
				Order_Class::getOrderDistributionStatusText($val),
				$strGoods,
			);
			$reportObj->setData($insertData);
		}
		$reportObj->toDownload();
	}

	//修改商户信息
	public function seller_edit()
	{
		$seller_id = $this->seller['seller_id'];
		$sellerDB        = new IModel('seller');
		$this->sellerRow = $sellerDB->getObj('id = '.$seller_id);
		$this->redirect('seller_edit');
	}

	/**
	 * @brief 商户的增加动作
	 */
	public function seller_add()
	{
		//print_r($_FILES);
		//die;
		
		$seller_id   = $this->seller['seller_id'];
		$email       = IFilter::act(IReq::get('email'));
		$password    = IFilter::act(IReq::get('password'));
		$repassword  = IFilter::act(IReq::get('repassword'));
		$phone       = IFilter::act(IReq::get('phone'));
		$mobile      = IFilter::act(IReq::get('mobile'));
		$province    = IFilter::act(IReq::get('province'),'int');
		$city        = IFilter::act(IReq::get('city'),'int');
		$area        = IFilter::act(IReq::get('area'),'int');
		$address     = IFilter::act(IReq::get('address'));
		$account     = IFilter::act(IReq::get('account'));
		$server_num  = IFilter::act(IReq::get('server_num'));
		$home_url    = IFilter::act(IReq::get('home_url'));
		$tax         = IFilter::act(IReq::get('tax'),'float');
		$plate_id    = IFilter::act(IReq::get('plate_id'),'int');
		$store_name  = IFilter::act(IReq::get('store_name')); 

		//echo "seller_id is $seller_id<br/>email is $email<br/>password is $password<br/>repassword is $repassword<br/>phone is $phone <br/>mobile is $mobile<br/>province is $province<br/>city is $city<br/>";
		//echo "area is $area<br/>address is $address<br/>account is $account<br/>server_num is $server_num<br/>home_url is $home_url<br/>tax is $tax<br/>plate_id is $plate_id<br/>store_name is $store_name";
		
		//die;
		
		if(!$seller_id && $password == '')
		{
			$errorMsg = '请输入密码！';
		}
        
		if($password != $repassword)
		{
			$errorMsg = '两次输入的密码不一致！';
		}
		
		//查询店铺名是否有重复
		//$sellerDB        = new IModel('seller');
		//$store = $sellerDB->getObj('store_name = '.$store_name);
		//if(!empty($store)){
		//    $errorMsg = '该店铺名已被使用！';
		//}
		
		//操作失败表单回填
		if(isset($errorMsg))
		{
			
			$this->sellerRow = $_POST;
			$this->redirect('seller_edit',false);
			Util::showMessage($errorMsg);
		}
		
		//待更新的数据
		$sellerRow = array(
			'account'   => $account,
			'phone'     => $phone,
			'mobile'    => $mobile,
			'email'     => $email,
			'address'   => $address,
			'province'  => $province,
			'city'      => $city,
			'area'      => $area,
			'server_num'=> $server_num,
			'home_url'  => $home_url,
			'tax'       => $tax,
		    'plate_id'  => $plate_id,
		    //'store_name'=> $store_name,
		);
		//商户资质上传
		if(isset($_FILES['store_img']['name']) && $_FILES['store_img']['name'])
		{
			
		    $uploadObj = new PhotoUpload();
		    $uploadObj->setIterance(false);
		    $photoInfo = $uploadObj->run();
		    if(isset($photoInfo['store_img']['img'])) //&& file_exists($photoInfo['store_img']['img'])
		    {
		        $sellerRow['store_img'] = $photoInfo['store_img']['img'];
				//die($sellerRow['store_img']);
		    }
			//die("not in if");
		}	
		//创建商家操作类
		$sellerDB   = new IModel("seller");

		//修改密码
		if($password)
		{
			$sellerRow['password'] = md5($password);
		}

		$sellerDB->setData($sellerRow);
		$sellerDB->update("id = ".$seller_id);

		$this->redirect('seller_edit');
	}
    
	//兑换码兑换
	function vr_order_exchange_show(){
	    $seller_id      = IFilter::act(IReq::get('seller_id'),'int');
	    $vr_code      = IFilter::act(IReq::get('vr_code'));
	    if(!empty($vr_code)){
    	    if(strlen($vr_code) == 18){
    	    $vrOrderCodeObj = new IModel('vr_order_code');
    	    $vrOrderCodeList = $vrOrderCodeObj->getObj('store_id = '.$seller_id.' AND vr_code = '.$vr_code);
    	       if(!empty($vrOrderCodeList)){
    	           if($vrOrderCodeList['vr_state'] == 0){
    	               
        	           $order_no = $vrOrderCodeList['order_no'];
        	           $vr_order_goodsObj = new IModel('vr_order_goods');
        	           $vr_order_goodsInfo = $vr_order_goodsObj->getObj('order_no = '.$order_no);
        	           $goods_id = $vr_order_goodsInfo['goods_id'];
        	           $goodsObj = new IModel('goods');
        	           $goodsInfo = $goodsObj->getObj('id = '.$goods_id);
        	           
        	           $updateData = array(
        	               'vr_state' => "1",
        	               'vr_usetime' => ITime::getDateTime(),
        	           );
        	           $commentDB = new IModel('vr_order_code');
        	           $commentDB->setData($updateData);
        	           $commentDB->update('vr_code = '.$vr_code);
        	           
        	           $this->goods_name = $goodsInfo['name'];
        	           $this->vr_order_code = $vrOrderCodeList['vr_code'];
        	           $this->order_no = $order_no;
        	           $this->goods_id = $goods_id;
        	           $this->vr_code = $vr_code;
        	           $this->isUse = "已确认，兑换成功";
        	           $this->redirect('vr_order_exchange_show');
    	           }else{
    	               IError::show(403,'该服务码已兑换，请勿重复兑换');
    	           }
    	       }else{
    	           IError::show(403,'没有查到该兑换码');
    	       }
    	    }else{
    	        IError::show(403,'该兑换码长度不正确，请重新输入');
    	    }
	    }else{
	        $this->redirect('vr_order_exchange_show');
	    }
	}
	
	//[团购]添加修改[单页]
	function regiment_edit()
	{
		$id = IFilter::act(IReq::get('id'),'int');

		if($id)
		{
			$regimentObj = new IModel('regiment');
			$where       = 'id = '.$id.' and seller_id = '.$this->seller['seller_id'];
			$regimentRow = $regimentObj->getObj($where);
			if(!$regimentRow)
			{
				$this->redirect('regiment_list');
			}

			//促销商品
			$goodsObj = new IModel('goods');
			$goodsRow = $goodsObj->getObj('id = '.$regimentRow['goods_id']);

			$result = array(
				'isError' => false,
				'data'    => $goodsRow,
			);
			$regimentRow['goodsRow'] = JSON::encode($result);
			$this->regimentRow = $regimentRow;
		}
		$this->redirect('regiment_edit');
	}

	//[团购]删除
	function regiment_del()
	{
		$id = IFilter::act(IReq::get('id'),'int');
		if($id)
		{
			$regObj = new IModel('regiment');
			if(is_array($id))
			{
				$id    = join(',',$id);
			}
			$where = ' id in ('.$id.') and seller_id = '.$this->seller['seller_id'];
			$regObj->del($where);
			$this->redirect('regiment_list');
		}
		else
		{
			$this->redirect('regiment_list',false);
			Util::showMessage('请选择要删除的id值');
		}
	}

	//[团购]添加修改[动作]
	function regiment_edit_act()
	{
		$id      = IFilter::act(IReq::get('id'),'int');
		$goodsId = IFilter::act(IReq::get('goods_id'),'int');

		$dataArray = array(
			'id'        	=> $id,
			'title'     	=> IFilter::act(IReq::get('title','post')),
			'start_time'	=> IFilter::act(IReq::get('start_time','post')),
			'end_time'  	=> IFilter::act(IReq::get('end_time','post')),
			'is_close'      => 1,
			'intro'     	=> IFilter::act(IReq::get('intro','post')),
			'goods_id'      => $goodsId,
			'store_nums'    => IFilter::act(IReq::get('store_nums','post')),
			'limit_min_count' => IFilter::act(IReq::get('limit_min_count','post'),'int'),
			'limit_max_count' => IFilter::act(IReq::get('limit_max_count','post'),'int'),
			'regiment_price'=> IFilter::act(IReq::get('regiment_price','post')),
			'seller_id'     => $this->seller['seller_id'],
		);

		$dataArray['limit_min_count'] = $dataArray['limit_min_count'] <= 0 ? 1 : $dataArray['limit_min_count'];
		$dataArray['limit_max_count'] = $dataArray['limit_max_count'] <= 0 ? $dataArray['store_nums'] : $dataArray['limit_max_count'];

		if($goodsId)
		{
			$goodsObj = new IModel('goods');
			$where    = 'id = '.$goodsId.' and seller_id = '.$this->seller['seller_id'];
			$goodsRow = $goodsObj->getObj($where);

			//商品信息不存在
			if(!$goodsRow)
			{
				$this->regimentRow = $dataArray;
				$this->redirect('regiment_edit',false);
				Util::showMessage('请选择商户自己的商品');
			}

			//处理上传图片
			if(isset($_FILES['img']['name']) && $_FILES['img']['name'] != '')
			{
				$uploadObj = new PhotoUpload();
				$photoInfo = $uploadObj->run();
				$dataArray['img'] = $photoInfo['img']['img'];
			}
			else
			{
				$dataArray['img'] = $goodsRow['img'];
			}

			$dataArray['sell_price'] = $goodsRow['sell_price'];
		}
		else
		{
			$this->regimentRow = $dataArray;
			$this->redirect('regiment_edit',false);
			Util::showMessage('请选择要关联的商品');
		}

		$regimentObj = new IModel('regiment');
		$regimentObj->setData($dataArray);

		if($id)
		{
			$where = 'id = '.$id.' and seller_id = '.$this->seller['seller_id'];
			$regimentObj->update($where);
		}
		else
		{
			$regimentObj->add();
		}
		$this->redirect('regiment_list');
	}

	//结算单修改
	public function bill_edit()
	{
		$id = IFilter::act(IReq::get('id'),'int');
		$billRow = array();

		if($id)
		{
			$billDB  = new IModel('bill');
			$billRow = $billDB->getObj('id = '.$id.' and seller_id = '.$this->seller['seller_id']);
		}

		$this->billRow = $billRow;
		$this->redirect('bill_edit');
	}

	//结算单删除
	public function bill_del()
	{
		$id = IFilter::act(IReq::get('id'),'int');

		if($id)
		{
			$billDB = new IModel('bill');
			$billDB->del('id = '.$id.' and seller_id = '.$this->seller['seller_id'].' and is_pay = 0');
		}

		$this->redirect('bill_list');
	}

	//结算单更新
	public function bill_update()
	{
	    $id            = IFilter::act(IReq::get('id'),'int');
		$start_time    = IFilter::act(IReq::get('start_time'));
		$end_time      = IFilter::act(IReq::get('end_time'));
		$apply_content = IFilter::act(IReq::get('apply_content'));//备注
		
		
		$billDB = new IModel('bill');

		if($id)
		{
			$billRow = $billDB->getObj('id = '.$id);
			if($billRow['is_pay'] == 0)
			{
				$billDB->setData(array('apply_content' => $apply_content));
				$billDB->update('id = '.$id.' and seller_id = '.$this->seller['seller_id']);
			}
		}
		else
		{
			//判断是否存在未处理的申请
			$isSubmitBill = $billDB->getObj(" seller_id = ".$this->seller['seller_id']." and is_pay = 0");
			if($isSubmitBill)
			{
				$this->redirect('bill_list',false);
				Util::showMessage('请耐心等待管理员结算后才能再次提交申请');
			}

			//获取未结算的订单
// 			$queryObject = CountSum::getSellerGoodsFeeQuery($this->seller['seller_id'],$start_time,$end_time,0);
// 			$countData   = CountSum::countSellerOrderFee($queryObject->find());

			$dataArray = array();
			//拿出order对象
			$queryObject = CountSum::getSellerGoodsFeeQuery($this->seller['seller_id'],$start_time,$end_time,0);
			$queryVrObject = CountSum::getSellerVrGoodsFeeQuery($this->seller['seller_id'],$start_time,$end_time,0);
			//$queryObject->find() : 查出order表里的信息
			$dataArray = $queryObject->find();
			//print_r($countData);
			//die;
			$vrOrderList = $queryVrObject->find();
			if(!empty($vrOrderList)){
			    foreach ($vrOrderList as $vrOrder){
			        array_push($dataArray,$vrOrder);
			    }
			}
			
			
			$oder_ids = "";	
			foreach ($dataArray as $k=>$v){
				$oder_ids = $oder_ids.",".$v['id'];
			}
			//结算信息
			$countData   = CountSum::countSellerOrderFee($dataArray);
			
			if($countData['countFee'] > 0)
			{
			    
				$countData['start_time'] = $start_time;
				$countData['end_time']   = $end_time;
				
				//$billString = AccountLog::sellerBillTemplate($countData);
				$billString = json_encode($countData,JSON_UNESCAPED_UNICODE);
				/* echo "<pre>";
				echo $billString;
				echo "</pre>";
				die; */
				$data = array(
					'seller_id'     => $this->seller['seller_id'],
					'apply_time'    => ITime::getDateTime(),
					'apply_content' => IFilter::act(IReq::get('apply_content')),
					'start_time'    => $start_time,
					'end_time'      => $end_time,
					'log'           => $billString,
					'order_ids'     => $oder_ids,
					'amount'        => $countData['countFee'],
				);
				$billDB->setData($data);
				$billDB->add();
			}
			else
			{
				$this->redirect('bill_list',false);
				Util::showMessage('当前时间段内没有任何结算货款');
			}
		}
		$this->redirect('bill_list');
	}

	//计算应该结算的货款明细
	public function countGoodsFee()
	{
	    //echo "ok";die;
		$seller_id   = $this->seller['seller_id'];
	    //$seller_id = 6;
		$start_time  = IFilter::act(IReq::get('start_time'));
		$end_time    = IFilter::act(IReq::get('end_time'));
	   // $start_time = "2017-05-01";
	   // $end_time = "2017-05-11";
	    //file_put_contents("./time.txt",$start_time." ".$end_time);
	    $dataArray = array();
		//拿出order对象
		$queryObject = CountSum::getSellerGoodsFeeQuery($seller_id,$start_time,$end_time,0);
		$queryVrObject = CountSum::getSellerVrGoodsFeeQuery($seller_id,$start_time,$end_time,0);
		//$queryObject->find() : 查出order表里的信息
		$dataArray = $queryObject->find();
		$vrOrderList = $queryVrObject->find();
		if(!empty($vrOrderList)){
    		foreach ($vrOrderList as $vrOrder){
    		    array_push($dataArray,$vrOrder);
    		}
		}
		$countData   = CountSum::countSellerOrderFee($dataArray);
		//print_r($countData);
		//die;
		//file_put_contents("./test.txt",JSON::encode($dataArray));
		if($countData['countFee'] > 0)
		{
		   
		    $countData['result'] = "success";
		    $result = $countData;
		    
		      
		    
		    
		    
		   /*  $jisuandate = json_encode($countData,JSON_UNESCAPED_UNICODE);
		    echo "<pre>";
		    echo $jisuandate;
		    echo "</pre>";
		    die; */
		    
			//$countData['start_time'] = $start_time;
			//$countData['end_time']   = $end_time;
			//file_put_contents("./test3.txt",JSON::encode($countData));
			//$billString = AccountLog::sellerBillTemplate($countData);
			//$result     = array('result' => 'success','data' => $billString);
		}
		else
		{
			$result = array('result' => 'fail','data' => '当前没有任何款项可以结算');
		}

		die(JSON::encode($result));
	}

	/**
	 * @brief 显示评论信息
	 */
	function comment_edit()
	{
		$cid = IFilter::act(IReq::get('cid'),'int');

		if(!$cid)
		{
			$this->comment_list();
			return false;
		}
		$query = new IQuery("comment as c");
		$query->join = "left join goods as goods on c.goods_id = goods.id left join user as u on c.user_id = u.id";
		$query->fields = "c.*,u.username,goods.name,goods.seller_id";
		$query->where = "c.id=".$cid." and goods.seller_id = ".$this->seller['seller_id'];
		$items = $query->find();

		if($items)
		{
			$this->comment = current($items);
			$this->redirect('comment_edit');
		}
		else
		{
			$this->comment_list();
			$msg = '没有找到相关记录！';
			Util::showMessage($msg);
		}
	}

	/**
	 * @brief 回复评论
	 */
	function comment_update()
	{
		$id = IFilter::act(IReq::get('id'),'int');
		$recontent = IFilter::act(IReq::get('recontents'));
		if($id)
		{
			$commentDB = new IQuery('comment as c');
			$commentDB->join = 'left join goods as go on go.id = c.goods_id';
			$commentDB->where= 'c.id = '.$id.' and go.seller_id = '.$this->seller['seller_id'];
			$checkList = $commentDB->find();
			if(!$checkList)
			{
				IError::show(403,'该商品不属于您，无法对其评论进行回复');
			}

			$updateData = array(
				'recontents' => $recontent,
				'recomment_time' => ITime::getDateTime(),
			);
			$commentDB = new IModel('comment');
			$commentDB->setData($updateData);
			$commentDB->update('id = '.$id);
		}
		$this->redirect('comment_list');
	}

	//商品退款详情
	function refundment_show()
	{
	 	//获得post传来的退款单id值
	 	$refundment_id = IFilter::act(IReq::get('id'),'int');
	 	$data = array();
	 	if($refundment_id)
	 	{
	 		$tb_refundment = new IQuery('refundment_doc as c');
	 		$tb_refundment->join=' left join order as o on c.order_id=o.id left join user as u on u.id = c.user_id';
	 		$tb_refundment->fields = 'u.username,c.*,o.*,c.id as id,c.pay_status as pay_status';
	 		$tb_refundment->where = 'c.id='.$refundment_id.' and c.seller_id = '.$this->seller['seller_id'];
	 		$refundment_info = $tb_refundment->find();
	 		if($refundment_info)
	 		{
	 			$data = current($refundment_info);
	 			$this->data = $data;
	 			$this->setRenderData($data);
	 			$this->redirect('refundment_show',false);
	 		}
	 	}

	 	if(!$data)
		{
			$this->redirect('refundment_list');
		}
	}

	//商品退款操作
	function refundment_update()
	{
		$id           = IFilter::act(IReq::get('id'),'int');
		$pay_status   = IFilter::act(IReq::get('pay_status'),'int');
		$dispose_idea = IFilter::act(IReq::get('dispose_idea'));
		$amount       = IFilter::act(IReq::get('amount'),'float');

		if(!$pay_status)
		{
			die('选择处理状态');
		}

		//商户处理退款
		if($id && Order_Class::isSellerRefund($id,$this->seller['seller_id']) == 2)
		{
			$updateData = array(
				'dispose_time' => ITime::getDateTime(),
				'dispose_idea' => $dispose_idea,
				'pay_status'   => $pay_status,
				'amount'       => $amount,
			);
			$tb_refundment_doc = new IModel('refundment_doc');
			$tb_refundment_doc->setData($updateData);
			$tb_refundment_doc->update('id = '.$id);

			if($pay_status == 2)
			{
				$result = Order_Class::refund($id,$this->seller['seller_id'],'seller');
				if(is_string($result))
				{
					$tb_refundment_doc->rollback();
					die($result);
				}
			}
		}
		$this->redirect('refundment_list');
	}

	//商品复制
	function goods_copy()
	{
		$idArray = explode(',',IReq::get('id'));
		$idArray = IFilter::act($idArray,'int');

		$goodsDB     = new IModel('goods');
		$goodsAttrDB = new IModel('goods_attribute');
		$goodsPhotoRelationDB = new IModel('goods_photo_relation');
		$productsDB = new IModel('products');

		$goodsData = $goodsDB->query('id in ('.join(',',$idArray).') and is_share = 1 and is_del = 0 and seller_id = 0','*');
		if($goodsData)
		{
			foreach($goodsData as $key => $val)
			{
				//判断是否重复
				if( $goodsDB->getObj('seller_id = '.$this->seller['seller_id'].' and name = "'.$val['name'].'"') )
				{
					die('商品不能重复复制');
				}

				$oldId = $val['id'];

				//商品数据
				unset($val['id'],$val['visit'],$val['favorite'],$val['sort'],$val['comments'],$val['sale'],$val['grade'],$val['is_share']);
				$val['seller_id'] = $this->seller['seller_id'];
				$val['goods_no'] .= '-'.$this->seller['seller_id'];
				$val['name']      = IFilter::act($val['name'],'text');
				$val['content']   = IFilter::act($val['content'],'text');

				$goodsDB->setData($val);
				$goods_id = $goodsDB->add();

				//商品属性
				$attrData = $goodsAttrDB->query('goods_id = '.$oldId);
				if($attrData)
				{
					foreach($attrData as $k => $v)
					{
						unset($v['id']);
						$v['goods_id'] = $goods_id;
						$goodsAttrDB->setData($v);
						$goodsAttrDB->add();
					}
				}

				//商品图片
				$photoData = $goodsPhotoRelationDB->query('goods_id = '.$oldId);
				if($photoData)
				{
					foreach($photoData as $k => $v)
					{
						unset($v['id']);
						$v['goods_id'] = $goods_id;
						$goodsPhotoRelationDB->setData($v);
						$goodsPhotoRelationDB->add();
					}
				}

				//货品
				$productsData = $productsDB->query('goods_id = '.$oldId);
				if($productsData)
				{
					foreach($productsData as $k => $v)
					{
						unset($v['id']);
						$v['products_no'].= '-'.$this->seller['seller_id'];
						$v['goods_id']    = $goods_id;
						$productsDB->setData($v);
						$productsDB->add();
					}
				}
			}
			die('success');
		}
		else
		{
			die('复制的商品不存在');
		}
	}

	/**
	 * @brief 添加/修改发货信息
	 */
	public function ship_info_edit()
	{
		// 获取POST数据
    	$id = IFilter::act(IReq::get("sid"),'int');
    	if($id)
    	{
    		$tb_ship   = new IModel("merch_ship_info");
    		$ship_info = $tb_ship->getObj("id=".$id." and seller_id = ".$this->seller['seller_id']);
    		if($ship_info)
    		{
    			$this->data = $ship_info;
    		}
    		else
    		{
    			die('数据不存在');
    		}
    	}
    	$this->setRenderData($this->data);
		$this->redirect('ship_info_edit');
	}
	/**
	 * @brief 设置发货信息的默认值
	 */
	public function ship_info_default()
	{
		$id = IFilter::act( IReq::get('id'),'int' );
        $default = IFilter::string(IReq::get('default'));
        $tb_merch_ship_info = new IModel('merch_ship_info');
        if($default == 1)
        {
            $tb_merch_ship_info->setData(array('is_default'=>0));
            $tb_merch_ship_info->update("seller_id = ".$this->seller['seller_id']);
        }
        $tb_merch_ship_info->setData(array('is_default' => $default));
        $tb_merch_ship_info->update("id = ".$id." and seller_id = ".$this->seller['seller_id']);
        $this->redirect('ship_info_list');
	}
	/**
	 * @brief 保存添加/修改发货信息
	 */
	public function ship_info_update()
	{
		// 获取POST数据
    	$id = IFilter::act(IReq::get('sid'),'int');
    	$ship_name = IFilter::act(IReq::get('ship_name'));
    	$ship_user_name = IFilter::act(IReq::get('ship_user_name'));
    	$sex = IFilter::act(IReq::get('sex'),'int');
    	$province =IFilter::act(IReq::get('province'),'int');
    	$city = IFilter::act(IReq::get('city'),'int');
    	$area = IFilter::act(IReq::get('area'),'int');
    	$address = IFilter::act(IReq::get('address'));
    	$postcode = IFilter::act(IReq::get('postcode'),'int');
    	$mobile = IFilter::act(IReq::get('mobile'));
    	$telphone = IFilter::act(IReq::get('telphone'));
    	$is_default = IFilter::act(IReq::get('is_default'),'int');

    	$tb_merch_ship_info = new IModel('merch_ship_info');

    	//判断是否已经有了一个默认地址
    	if(isset($is_default) && $is_default==1)
    	{
    		$tb_merch_ship_info->setData(array('is_default' => 0));
    		$tb_merch_ship_info->update('seller_id = 0');
    	}
    	//设置存储数据
    	$arr['ship_name'] = $ship_name;
	    $arr['ship_user_name'] = $ship_user_name;
	    $arr['sex'] = $sex;
    	$arr['province'] = $province;
    	$arr['city'] =$city;
    	$arr['area'] =$area;
    	$arr['address'] = $address;
    	$arr['postcode'] = $postcode;
    	$arr['mobile'] = $mobile;
    	$arr['telphone'] =$telphone;
    	$arr['is_default'] = $is_default;
    	$arr['is_del'] = 1;
    	$arr['seller_id'] = $this->seller['seller_id'];

    	$tb_merch_ship_info->setData($arr);
    	//判断是添加还是修改
    	if($id)
    	{
    		$tb_merch_ship_info->update('id='.$id." and seller_id = ".$this->seller['seller_id']);
    	}
    	else
    	{
    		$tb_merch_ship_info->add();
    	}
		$this->redirect('ship_info_list');
	}
	/**
	 * @brief 删除发货信息到回收站中
	 */
	public function ship_info_del()
	{
		// 获取POST数据
    	$id = IFilter::act(IReq::get('id'),'int');
		//加载 商家发货点信息
    	$tb_merch_ship_info = new IModel('merch_ship_info');
		if($id)
		{
			$tb_merch_ship_info->del(Util::joinStr($id)." and seller_id = ".$this->seller['seller_id']);
			$this->redirect('ship_info_list');
		}
		else
		{
			$this->redirect('ship_info_list',false);
			Util::showMessage('请选择要删除的数据');
		}
	}

	/**
	 * @brief 配送方式修改
	 */
    public function delivery_edit()
	{
		$data = array();
        $delivery_id = IFilter::act(IReq::get('id'),'int');

        if($delivery_id)
        {
            $delivery = new IModel('delivery_extend');
            $data = $delivery->getObj('delivery_id = '.$delivery_id.' and seller_id = '.$this->seller['seller_id']);
		}
		else
		{
			die('配送方式');
		}

		//获取省份
		$areaData = array();
		$areaDB = new IModel('areas');
		$areaList = $areaDB->query('parent_id = 0');
		foreach($areaList as $val)
		{
			$areaData[$val['area_id']] = $val['area_name'];
		}
		$this->areaList  = $areaList;
		$this->data_info = $data;
		$this->area      = $areaData;
        $this->redirect('delivery_edit');
	}

	/**
	 * 配送方式修改
	 */
    public function delivery_update()
    {
        //首重重量
        $first_weight = IFilter::act(IReq::get('first_weight'),'float');
        //续重重量
        $second_weight = IFilter::act(IReq::get('second_weight'),'float');
        //首重价格
        $first_price = IFilter::act(IReq::get('first_price'),'float');
        //续重价格
        $second_price = IFilter::act(IReq::get('second_price'),'float');
        //是否支持物流保价
        $is_save_price = IFilter::act(IReq::get('is_save_price'),'int');
        //地区费用类型
        $price_type = IFilter::act(IReq::get('price_type'),'int');
        //启用默认费用
        $open_default = IFilter::act(IReq::get('open_default'),'int');
        //支持的配送地区ID
        $area_groupid = serialize(IReq::get('area_groupid'));
        //配送地址对应的首重价格
        $firstprice = serialize(IReq::get('firstprice'));
        //配送地区对应的续重价格
        $secondprice = serialize(IReq::get('secondprice'));
        //保价费率
        $save_rate = IFilter::act(IReq::get('save_rate'),'float');
        //最低保价
        $low_price = IFilter::act(IReq::get('low_price'),'float');
		//配送ID
        $delivery_id = IFilter::act(IReq::get('deliveryId'),'int');

        $deliveryDB  = new IModel('delivery');
        $deliveryRow = $deliveryDB->getObj('id = '.$delivery_id);
        if(!$deliveryRow)
        {
        	die('配送方式不存在');
        }

        //如果选择指定地区配送就必须要选择地区
        if($price_type == 1 && !$area_groupid)
        {
			die('请设置配送地区');
        }

        $data = array(
        	'first_weight' => $first_weight,
        	'second_weight'=> $second_weight,
        	'first_price'  => $first_price,
        	'second_price' => $second_price,
        	'is_save_price'=> $is_save_price,
        	'price_type'   => $price_type,
        	'open_default' => $open_default,
        	'area_groupid' => $area_groupid,
        	'firstprice'   => $firstprice,
        	'secondprice'  => $secondprice,
        	'save_rate'    => $save_rate,
        	'low_price'    => $low_price,
        	'seller_id'    => $this->seller['seller_id'],
        	'delivery_id'  => $delivery_id,
        );
        $deliveryExtendDB = new IModel('delivery_extend');
        $deliveryExtendDB->setData($data);
        $deliveryObj = $deliveryExtendDB->getObj("delivery_id = ".$delivery_id." and seller_id = ".$this->seller['seller_id']);
        //已经存在了
        if($deliveryObj)
        {
        	$deliveryExtendDB->update('delivery_id = '.$delivery_id.' and seller_id = '.$this->seller['seller_id']);
        }
        else
        {
        	$deliveryExtendDB->add();
        }
		$this->redirect('delivery');
    }

	//[促销活动] 添加修改 [单页]
	function pro_rule_edit()
	{
		$id = IFilter::act(IReq::get('id'),'int');
		if($id)
		{
			$promotionObj = new IModel('promotion');
			$where = 'id = '.$id.' and seller_id='.$this->seller['seller_id'];
			$this->promotionRow = $promotionObj->getObj($where);
		}
		$this->redirect('pro_rule_edit');
	}

	//[促销活动] 添加修改 [动作]
	function pro_rule_edit_act()
	{
		$id           = IFilter::act(IReq::get('id'),'int');
		$user_group   = IFilter::act(IReq::get('user_group','post'));
		$promotionObj = new IModel('promotion');
		if(is_string($user_group))
		{
			$user_group_str = $user_group;
		}
		else
		{
			$user_group_str = ",".join(',',$user_group).",";
		}

		$dataArray = array(
			'name'       => IFilter::act(IReq::get('name','post')),
			'condition'  => IFilter::act(IReq::get('condition','post')),
			'is_close'   => IFilter::act(IReq::get('is_close','post')),
			'start_time' => IFilter::act(IReq::get('start_time','post')),
			'end_time'   => IFilter::act(IReq::get('end_time','post')),
			'intro'      => IFilter::act(IReq::get('intro','post')),
			'award_type' => IFilter::act(IReq::get('award_type','post')),
			'type'       => 0,
			'user_group' => $user_group_str,
			'award_value'=> IFilter::act(IReq::get('award_value','post')),
			'seller_id'  => $this->seller['seller_id'],
		);

		if(!in_array($dataArray['award_type'],array(1,2,6)))
		{
			IError::show('促销类型不符合规范',403);
		}

		$promotionObj->setData($dataArray);

		if($id)
		{
			$where = 'id = '.$id;
			$promotionObj->update($where);
		}
		else
		{
			$promotionObj->add();
		}
		$this->redirect('pro_rule_list');
	}

	//[促销活动] 删除
	function pro_rule_del()
	{
		$id = IFilter::act(IReq::get('id'),'int');
		if(!empty($id))
		{
			$promotionObj = new IModel('promotion');
			if(is_array($id))
			{
				$idStr = join(',',$id);
				$where = ' id in ('.$idStr.')';
			}
			else
			{
				$where = 'id = '.$id;
			}
			$promotionObj->del($where.' and seller_id = '.$this->seller['seller_id']);
			$this->redirect('pro_rule_list');
		}
		else
		{
			$this->redirect('pro_rule_list',false);
			Util::showMessage('请选择要删除的促销活动');
		}
	}

	//修改订单价格
	public function order_discount()
	{
		$order_id = IFilter::act(IReq::get('order_id'),'int');
		$discount = IFilter::act(IReq::get('discount'),'float');
		$orderDB  = new IModel('order');
		$orderRow = $orderDB->getObj('id = '.$order_id.' and status = 1 and distribution_status = 0 and seller_id = '.$this->seller['seller_id']);
		if($orderRow)
		{
			//还原价格
			$newOrderAmount = ($orderRow['order_amount'] - $orderRow['discount']) + $discount;
			$orderDB->setData(array('discount' => $discount,'order_amount' => $newOrderAmount));
			if($orderDB->update('id = '.$order_id))
			{
				die(JSON::encode(array('result' => true,'orderAmount' => $newOrderAmount)));
			}
		}
		die(JSON::encode(array('result' => false)));
	}

	// 消息通知
	public function message_list()
	{
		$page   = IReq::get('page') ? IFilter::act(IReq::get('page'),'int') : 1;
		$seller_messObject = new seller_mess($this->seller['seller_id']);
		$msgIds = $seller_messObject->getAllMsgIds();
		$msgIds = empty($msgIds) ? 0 : $msgIds;
		$needReadNum = $seller_messObject->needReadNum();

		$seller_messageHandle = new IQuery('seller_message');
		$seller_messageHandle->where = "id in(".$msgIds.")";
		$seller_messageHandle->order= "id desc";
		$seller_messageHandle->page = $page;

		$this->needReadNum = $needReadNum;
		$this->seller_messObject = $seller_messObject;
		$this->seller_messageHandle = $seller_messageHandle;

		$this->redirect("message_list");
	}

	// 消息详情
	public function message_show()
	{
		$id = IFilter::act(IReq::get('id'),'int');
		if (!empty($id))
		{
			$seller_messObject = new seller_mess($this->seller['seller_id']);
			$seller_messObject->writeMessage($id, 1);
		}
		$this->redirect('message_show');
	}

	// 消息删除
	public function message_del()
	{
		$id = IFilter::act(IReq::get('id'),'int');
		if (!empty($id))
		{
			$seller_messObject = new seller_mess($this->seller['seller_id']);
			if (is_array($id)) {
				foreach ($id as $val)
				{
					$seller_messObject->delMessage($val);
				}
			}else {
				$seller_messObject->delMessage($id);
			}
		}
		$this->redirect('message_list');
	}

	//订单备注
	public function order_note()
	{
	 	//获得post数据
	 	$order_id = IFilter::act(IReq::get('order_id'),'int');
	 	$note = IFilter::act(IReq::get('note'),'text');

	 	//获得order的表对象
	 	$tb_order =  new IModel('order');
	 	$tb_order->setData(array(
	 		'note'=>$note
	 	));
	 	$tb_order->update('id = '.$order_id.' and seller_id = '.$this->seller['seller_id']);
	 	$this->redirect("/seller/order_show/id/".$order_id,true);
	}

	/**
	 * @brief 删除咨询信息
	 */
	function refer_del()
	{
		$refer_ids = IFilter::act(IReq::get('id'),'int');
		$refer_ids = is_array($refer_ids) ? $refer_ids : array($refer_ids);
		if($refer_ids)
		{
			$ids = join(',',$refer_ids);
			if($ids)
			{
				//查询咨询的商品是否属于当前商户
				$referDB        = new IQuery('refer as re,goods as go');
				$referDB->where = "re.id in (".$ids.") and re.goods_id = go.id and go.seller_id = ".$this->seller['seller_id'];
				$referDB->fields= "re.id";
				$referGoods     = $referDB->find();
				$referModel     = new IModel('refer');
				foreach($referGoods as $reId)
				{
					$referModel->del("id = ".$reId['id']);
				}
			}
		}
		$this->redirect('refer_list');
	}
	
	//获取即时未读信息
	function userchatlist(){
	    $u_id = $_GET['f_id'];
	
	    if($u_id == "请重新登陆" || $u_id == ""){
	        echo "请重新登陆";
	        return ;
	    }
	     
	    $chat_msg = new IQuery("chat_msg");
	    $chat_msg->fields = "COUNT(*) AS num,f_id,f_name,r_state";
	    $chat_msg->where  = "r_state = 2 AND t_id = ".$u_id;
	    $chat_msg->group  = "f_id";
	    $date = $chat_msg->find();
	     
	    /*if(empty($date)){
	     echo "";
	     return ;
	    }*/
	    //$res = json_encode($date,JSON_UNESCAPED_UNICODE);
	    $this->setRenderData(array("dates"=>$date));
	    $this->redirect('userchatlist',false);
	}
	
	//商家手机版聊天处理
	function mobil_chat(){
	    
	    $seller_id = ISafe::get('seller_id');
	    if(empty($seller_id)){
	        echo "非法操作,请重新登录再试";
	        die;
	    }
	   
	    
	    $s_memberModel = new IModel('seller');
	    $u_Model = new IModel('user');
	    
	    //送者信息
	    $s_member = $s_memberModel->getObj('id = '.$seller_id);
        $f_id = $s_member['member_id'];
        $f_user = $u_Model->getObj('id = '.$f_id);
        
        $t_id = $_GET['t_id'];
        
        if(empty($t_id)){
            echo "获取联系人失败";
            die;
        }
        //接收信息
        $t_user = $u_Model->getObj('id = '.$t_id);
        
        //添加临时好友
        $model = new IModel('friends');
         
        $fquery = new IQuery('friends as f');
        $where = ('f.f_id = '.$f_id .' AND '.'f.t_id = '.$t_id).' OR '.('f.f_id = '.$t_id.' AND '.'f.t_id = '.$f_id);
        $fquery->where = $where;
        $result = $fquery->find();
        //不存在数据
        if(!$result){
            $data = array(
                "f_id"      => $f_id,
                'f_name'    =>$f_user['username'],
                't_id'      =>$t_id,
                't_name'    =>$t_user['username'],
                'addtime'   =>date("Y-m-d H:i:s")
            );
             
            $model->setData($data);
            $addresult = $model->add();
        }
        
        $arr = array(
            "t_id" =>$t_id,
            "t_name"=>$t_user['username'],
            "t_ava" =>$t_user['head_ico'],
            'f_id' =>$f_id,
            'f_name'   =>$f_user['username'],
            "f_ava"    =>$f_user['head_ico']
        );
         
        $date = array(
            "item"=> $arr
        );
        
        $this->setRenderData($date);
        $this->redirect('chat',false);
	}
	
	
	//商家的个人中心
	function seller_center(){
	   // print_r($this->seller['seller_id']);
	    
	    //$seller_id = $this->seller['seller_id'];
	    $seller = new IQuery('seller as s');
	    $seller->join=' left join user as u on s.member_id = u.id left join member as m on u.id = m.user_id';
	    $seller->fields = '*';
	    $seller->where = 's.id = '.$this->seller['seller_id'];
	    $result = $seller->find();
	    
	   
	    
	    $this->setRenderData(array("res"=>$result));
	    $this->redirect('seller_center');
	}
	
	//申请开通板块
	function more_plate(){
		//print_r($this->seller);
		
	    
		$seller_db = new IModel('seller');
		$seller_id = $this->seller['seller_id'] ;
		$result = $seller_db->getObj('id = '.$seller_id);
		
		//print_r($result);
		
		//解压json
		$plates = json_decode($result['plates'],true);
		$res = "";
		foreach($plates as $v){
		    $res = $res . $v . "," ;
		}
		$str_length = strlen($res);
		$true_plates = substr($res,0,$str_length-1);
		
		$this->setRenderData(array("true_plates"=>$true_plates));
		$this->redirect('more_plate');
	}
	
	//板块申请
	function plate_apply(){
	    
	    $seller_id = $this->seller['seller_id'] ;
	    $seller_name = $this->seller['seller_name'] ;
	    $apply_plate = $_POST['seller_apply'];
	    if(empty($seller_id)){
	        die("非法用户");
	        return ;
	    }
	    
	    
	    $plate_applyObj = new IModel('plate_apply');
	    $arr = array(
	        "seller_id"=>$seller_id,
	        "seller_name"=>$seller_name,
	        "plate_id"=>$apply_plate,
	        "apply_time"=>ITime::getDateTime()
	    );
	    $plate_applyObj->setData($arr);
	    $id = $plate_applyObj->add();
	    
	    if($id){
	        $this->redirect('apply_success');
	        return ;
	    }else{
	        $this->redirect('apply_error');
	        return ;
	    }
	}
	
	//商家关联账户余额详情
	function account_log_user(){
	    
	   
	    $seller = new IQuery('seller as s');
	    $seller->join='left join account_log as al on s.member_id = al.user_id';
	    $seller->fields = '*';
	    $seller->where = 's.id = '.$this->seller['seller_id']." and al.user_id is not null";
	    $result = $seller->find();
	  //  $this->pri($result);
	    $this->setRenderData(array("account_log"=>$result));
	    $this->redirect('account_log_user');
	}
	
	function pri($arr){
	    echo "<pre>";
	    print_r($arr);
	    echo "</pre>";
	}
	
	
}



